package com.queryBuilder.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.queryBuilder.builer.BuilderBasic;

public class DocumentUtil {
	private static final Log log = LogFactory.getLog(BuilderBasic.class);
	private static final String XMLPATH = DocumentUtil.class.getClassLoader()
			.getResource(File.separator).getPath();

	/**
	 * 获取document对象
	 * 
	 * @param fileName
	 *            要获取的document对象的文件名称
	 * @return
	 */
	public static Document getDocument(String fileName) {
		Map<String, Object> map = null;
		// System.out.println("获取到的路径为：\t"+XMLPATH);
		SAXReader reader = new SAXReader();
		Document document = null;
		File file = null;
		try {
			file = new File(XMLPATH + File.separator + fileName);
			document = reader.read(file);
		} catch (DocumentException e) {
			log.error("获取" + fileName + "失败，请检查是否正确在根目录下创建此文件！");
			e.printStackTrace();
		}
		return document;
	}

	public static Map<String, Object> getDocumentAndFile(String fileName) {
		Map<String, Object> map = new HashMap<String, Object>();
		SAXReader reader = new SAXReader();
		Document document = null;
		File file = null;
		try {
			file = new File(XMLPATH + File.separator + fileName);
			document = reader.read(file);
			map.put("document", document);
			map.put("file", file);
		} catch (DocumentException e) {
			log.error("获取" + fileName + "失败，请检查是否正确在根目录下创建此文件！");
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 写入xml文档
	 * @param document
	 * @param file
	 * @return
	 */
	public static boolean writeToXml(Document document,File file) {
		try {  
            FileOutputStream fos = new FileOutputStream(file);  
            // 用于格式化输出  
             OutputFormat of = OutputFormat.createPrettyPrint();  
            // 格式化输出的另一个形式，不知这两种有什么区别  
            // 第1个参数为格式化输出缩排字符,此处为空格,第2个参数true为换行输出,false为单行输出  
//            OutputFormat of = new OutputFormat(" ", false);  
            // 输出为GBK码解决在windows下某些系统下打开含有中文xml乱码的情况  
            of.setEncoding("UTF-8");  
            XMLWriter xw = new XMLWriter(fos, of);  
            xw.write(document);  
            xw.close();  
        } catch (IOException e) {  
            log.error("保存模板失败。");
            return false;
        }  
		return true;
	}
}
